package com.example.restfull.validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created by wuning at 2018/10/22 16:58
 **/
public class UserNameValidator implements ConstraintValidator<UserNameConstraint,String> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * Initializes the validator in preparation for
     * {@link #isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(UserNameConstraint constraintAnnotation) {

        logger.info("initialize");
    }

    /**
     * Implements the validation logic.
     * The state of {@code value} must not be altered.
     * <p>
     * This method can be accessed concurrently, thread-safety must be ensured
     * by the implementation.
     *
     * @param value   object to validate
     * @param context context in which the constraint is evaluated
     * @return {@code false} if {@code value} does not pass the constraint
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        logger.info("try to valid {}",value);
        //这里写自定义的校验逻辑，return true表示验证通过，否则验证失败
        if (value == null || value.trim().equals("")){
            return false;
        }

        if (!value.startsWith("abc")){
            return false;
        }

        if (!value.endsWith("xyz")){
            return false;
        }

        return true;
    }
}
